package com.flute.framework.autoprompt;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import com.flute.tools.data.DataIterator;
import com.flute.tools.data.DataRecord;
import com.flute.tools.data.mysql.ConnectionInformation;
import com.flute.tools.data.mysql.NewMysqlHandler;

public class SongDataProvider implements IRecordProvider {
	Hashtable<String, Integer> map = new Hashtable<String, Integer>();

	public SongDataProvider() {
		ConnectionInformation info = new ConnectionInformation();
		info.setDbName("yyjd");
		info.setHost("localhost");
		info.setPassword("");
		info.setUserName("root");
		info.setPort("3306");
		NewMysqlHandler handler = new NewMysqlHandler(info);
		DataIterator<DataRecord> it = handler
				.iterator("select song_name,singer_names,album_names from quannei_song_indexdata limit 10");
		int i = 0;
		while (it.hasNext()) {
			DataRecord dr = it.next();
			countText(map, dr.getFieldValue("song_name"));
			countText(map, dr.getFieldValue("singer_names"));
			countText(map, dr.getFieldValue("album_names"));
			System.out.println("sql:" + i++);
		}
	}

	@Override
	public Iterator<TrainningToken> recordIterator() {
		return new Iterator<TrainningToken>() {
			Iterator<TrainningToken> tokenIt = null;
			Iterator<String> keyIt = map.keySet().iterator();

			@Override
			public boolean hasNext() {
				if (tokenIt == null || !tokenIt.hasNext()) {
					while (keyIt.hasNext()) {
						String key = keyIt.next();
						List<TrainningToken> tList = new CommonPriorityStrategy(
								2).getWordResult(key);
						for (TrainningToken tt : tList) {
							tt.getToken().updatePriority(map.get(key), 2);
						}
						tokenIt = tList.iterator();
						if (tokenIt.hasNext()) {
							return true;
						}
					}
				} else {
					return true;
				}

				return false;
			}

			@Override
			public TrainningToken next() {
				return tokenIt.next();
			}

			@Override
			public void remove() {
			}

		};
	}

	private static void countText(Hashtable<String, Integer> map, String text) {
		text = text.trim();
		if (!map.containsKey(text)) {
			map.put(text, 0);
		}
		map.put(text, map.get(text) + 1);
	}

}
